/**
 * Created by JLB1 on 2017/2/7.
 */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Clipboard from 'clipboard';
import AJAX from '../../lib/ajax';
import Tools from '../../lib/tools';
import wx from 'wx';
import Dialog from '../MyPackage/components/Dialog';
import Toast from '../MyPackage/components/Toast';
import AdBlock from '../../components/AdBlock'
import { addErrorListener } from '../../lib/handleError';
import weui from 'weui.js';


// require('../../styles/new-weui.less');
require('../../styles/common.less');
require('../../styles/lux.less');
require('../../styles/resetWeui.less');
require('./UnmannedCar.less');

// 单件金额
const singleton = 3;

class ExpressDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            unpick_list: [],
            station_list: [],
            time_list: [],

            has_unpick_list: [],
            has_station: false,
            has_time: '',
            remarks: '',
            canPay: false,
        };
        this.textArea = null;
        this.logisId = null;
        this.cur_price = 300; // 金额默认为300分一件，根据后台配置修改
    }

    componentWillMount() {
        addErrorListener()();

        // 取url参数，wx_type
        window.localStorage.setItem('wx_type', Tools.getParams().wx_type === 'garden' ? Tools.getParams().wx_type : 'logis');
        // Tools.createCookie('wx_type', Tools.getParams().wx_type);
    }

    componentDidMount() {

        this.logisId = Tools.getParams().logis_id;
        this.cur_price = Tools.getParams().price;
        // 获取该物流中心的未取件列表
        const params = {
            logis_id: this.logisId,
            page: 1,
            psize: 1000,
        };
        AJAX.request('logis_unpick_list', params, data => {
            const orderId = Tools.getParams().order_id;
            const order = data.body.list.find(item => item.id == orderId);
            console.log(order);
            this.setState({
                unpick_list: data.body.list,
                has_unpick_list: [{
                    billId: `${order.id}`,
                    type: order.storage_info.type,
                    address: order.storage_info.addr,
                    expressName: order.exp_name,
                    expNo: order.exp_code,
                    openCode: order.open_code,
                    cabinet: order.storage_info.cell_code
                }],
            });
        });
        // 获取该物流中心的站点列表
        AJAX.request('station_list', {
            logisId: this.logisId,
        }, data => {
            this.setState({
                station_list: data.body
            });
        });
        // 获取配送时间点列表
        AJAX.request('time_span', {
            logisId: this.logisId,
        }, data => {
            this.setState({
                time_list: data.body
            });
        });
    }

    handlePay = () => {
        const { has_unpick_list, has_station, has_time } = this.state;

        if (has_unpick_list.length < 1) {
            return Toast.warn({ content: '请至少选择一个快递' });
        }
        else if (!has_station) {
            return Toast.warn({ content: '请选择送达地址' });
        }
        else if (!has_time) {
            return Toast.warn({ content: '请选择送达时间' });
        }

        this.setState({ canPay: true });
        const billIds = [];
        has_unpick_list.map(item => {
            billIds.push(item.billId);
        })
        const params = {
            fee: has_unpick_list.length * this.cur_price,
            bills: billIds.join(),
        };
        AJAX.request('wechat_pay', params, (data) => {
            if (data.body.trade) {
                //成功，调用微信支付
                this.wxPay(data.body.trade.prepay, data.body.payId);
            } else {
                this.setState({ canPay: false });
            }
        }, window.location.href)
    }

    wxPay = (params, payId) => {
        const { has_unpick_list, has_station, has_time, remarks } = this.state;
        AJAX.request('get_signature', {
            full_url: window.location.href
        }, (data) => {

            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.body.appid, // 必填，公众号的唯一标识
                timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                signature: data.body.signature,// 必填，签名，见附录1
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            })
            wx.ready(() => {
                wx.chooseWXPay({
                    timestamp: params.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
                    package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: params.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: params.paySign, // 支付签名
                    success: () => {

                        this.setState({ canPay: false });
                        const create_params = {
                            order: {
                                logisId: this.logisId,
                                stationId: `${has_station.id}`,
                                stationName: has_station.name,
                                deliverTime: has_time,
                                comment: remarks,
                                payId: payId,
                                bills: has_unpick_list
                            }
                        };
                        // 支付成功后的回调函数
                        AJAX.request('unmanned_create', create_params, (data) => {
                            if (data.code === 0) {
                                // 新建订单成功后，要跳转 我的订单页面
                                sessionStorage.setItem('TAG', 'UNMANNED');
                                window.location.href = `./MyPackage`;
                            }
                        });
                    },
                    cancel: (res) => {
                        this.setState({ canPay: false });
                    },
                    fail: (reason) => {
                        this.setState({ canPay: false });
                    }
                })
            })
        })
    }


    render() {
        const {
            unpick_list,
            station_list,
            time_list,
            has_unpick_list,
            has_station,
            has_time,
            remarks,
            canPay
        } = this.state;



        return (
            <div>
                <div className="lux-pt10 lux-pl10 lux-pr10 lux-pb70">
                    <p style={{ fontSize: 16, color: '#333333', margin: '10px 0' }}>快递信息</p>
                    <div className="unpick-card">
                        <div className="unpick-list">
                            <div className="unpick-header">
                                <div className="weui-cells weui-cells_checkbox">
                                    {/* 全选订单 */}
                                    <div className="weui-cell weui-cell_active weui-check__label unpick-item" onClick={() => {
                                        event.preventDefault();
                                        event.stopPropagation();
                                        const newList = [];
                                        if (has_unpick_list.length !== unpick_list.length) {
                                            unpick_list.map(item => {
                                                if (item.pay_amount > 0) { return; }
                                                newList.push({
                                                    billId: `${item.id}`,
                                                    type: item.storage_info.type,
                                                    address: item.storage_info.addr,
                                                    expressName: item.exp_name,
                                                    expNo: item.exp_code,
                                                    openCode: item.open_code,
                                                    cabinet: item.storage_info.cell_code
                                                });
                                            })
                                        }
                                        this.setState({ has_unpick_list: newList });
                                    }}>
                                        <div className="weui-cell__hd">
                                            <input type="checkbox" className="weui-check" checked={has_unpick_list.length === unpick_list.length} />
                                            <i className="weui-icon-checked"></i>
                                        </div>
                                        <div className="weui-cell__bd lux-d-f lux-jc-sb">
                                            <p style={{ fontSize: 18, fontWeight: 'bold' }}>近邻宝快递</p>
                                            <p style={{ color: 'red' }}>已选{has_unpick_list.length}件</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="unpick-content">
                                <div className="weui-cells weui-cells_checkbox">
                                    {/* 订单列表 */}
                                    {unpick_list.map(item => {
                                        const index = has_unpick_list.findIndex(li => +li.billId === item.id);
                                        return (
                                            <div onClick={() => {
                                                event.preventDefault();
                                                event.stopPropagation();
                                                if (item.pay_amount > 0) { return; }
                                                const newList = [].concat(has_unpick_list);
                                                if (index > -1) {
                                                    newList.splice(index, 1);
                                                } else {
                                                    newList.push({
                                                        billId: `${item.id}`,
                                                        type: item.storage_info.type,
                                                        address: item.storage_info.addr,
                                                        expressName: item.exp_name,
                                                        expNo: item.exp_code,
                                                        openCode: item.open_code,
                                                        cabinet: item.storage_info.cell_code
                                                    });
                                                }
                                                this.setState({ has_unpick_list: newList });
                                            }}>
                                                <div className={`weui-cell weui-cell_active weui-check__label unpick-item ${item.pay_amount > 0 ? 'weui-cell_disabled' : ''}`}>
                                                    <div className="weui-cell__hd">
                                                        <input type="checkbox" className="weui-check" disabled={item.pay_amount > 0} checked={!!(index > -1)} />
                                                        <i className="weui-icon-checked"></i>
                                                    </div>
                                                    <div className="weui-cell__bd">
                                                        <p className="address">{item.storage_info.addr}</p>
                                                        <div className="lux-d-f lux-jc-sb">
                                                            <span className="express-info">{item.exp_name} {item.exp_code}</span>
                                                            <span className="box-num">{item.storage_info.type === 1 ? '箱门号' : '取件码'}：{item.storage_info.cell_code}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        )
                                    })}
                                </div>
                            </div>
                        </div>

                    </div>

                    <div className="unpick-card weui-form__control-area" style={{ margin: '10 0', }}>
                        <div className="weui-cells__group weui-cells__group_form">
                            <div className="weui-cell weui-cell_active weui-cell_select weui-cell_select-after" onClick={() => {
                                const data = [], that = this;
                                station_list.map(item => {
                                    data.push({
                                        label: item.stationName,
                                        value: item.stationId
                                    });
                                });
                                weui.picker(data, {
                                    onConfirm: function (result) {
                                        that.setState({
                                            has_station: {
                                                name: result[0].label,
                                                id: result[0].value
                                            }
                                        });
                                    },
                                    title: '无人车站点'
                                });
                            }}>
                                <div className="weui-cell__hd"><div className="weui-label">送达地址:</div></div>
                                <div className="weui-cell__bd"><div className={`weui-select ${has_station ? '' : 'lux-caaa'}`}>{has_station ? has_station.name : '请选择无人车站点'}</div></div>
                            </div>
                            <div className="weui-cell weui-cell_active weui-cell_select weui-cell_select-after" onClick={() => {
                                const data = [], that = this;
                                time_list.map(item => {
                                    data.push({
                                        label: item,
                                        value: item
                                    });
                                });
                                weui.picker(data, {
                                    onConfirm: function (result) {
                                        that.setState({
                                            has_time: result[0].value
                                        });
                                    },
                                    title: '配送时间'
                                });
                            }}>
                                <div className="weui-cell__hd"><div className="weui-label">配送时间:</div></div>
                                <div className="weui-cell__bd"><div className={`weui-select ${has_time ? '' : 'lux-caaa'}`}>{has_time || '请选择时间'}</div></div>
                            </div>
                            <div className="weui-cells__group weui-cells__group_form">
                                <div className="weui-cells__title" style={{ paddingLeft: 16, color: 'rgba(0, 0, 0, 0.9)', fontSize: 17, }}>问题描述</div>
                                <div className="weui-cells weui-cells_form">
                                    <div className="weui-cell weui-cell_active">
                                        <div className="weui-cell__bd">
                                            <textarea ref={node => this.textArea = node} maxLength="50" className="weui-textarea" placeholder="请描述你所发生的问题" rows="3" onChange={() => {
                                                this.setState({ remarks: this.textArea.value });
                                            }}></textarea>
                                            <div className="weui-textarea-counter"><span>{remarks.length}</span>/50</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="price">合计费用: <span style={{ color: 'red', fontSize: 22 }}>￥{has_unpick_list.length * this.cur_price / 100}</span></div>
                </div>
                <div className="footer-box">
                    <div className="footer-btn-box">
                        <button
                            className={'right-btn footer-btn'}
                            onClick={() => {
                                this.handlePay();
                            }}
                            disabled={canPay}
                        >
                            微信支付
                        </button>
                    </div>
                </div>

            </div >
        );
    }
}

ReactDOM.render(<ExpressDetail />, document.getElementById('app'));

if (module.hot) {
    module.hot.accept();
}